from selenium.common import StaleElementReferenceException, TimeoutException, NoSuchElementException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
import pages.webpage
from logs.logger import log
import allure


class BackupPage(pages.webpage.WebPage):
    url = "https://47.122.30.27:33023/5f40ca64"

    # 页面元素定位器
    advanced_btn_locator = (By.XPATH, "/html/body/div/div[2]/button[3]")
    proceed_link_locator = (By.XPATH, "/html/body/div/div[3]/p[2]/a")
    username_locator = (By.XPATH, "/html/body/div[1]/div/div/aside[3]/div/div[2]/div[1]/div/input")
    password_locator = (By.XPATH, "/html/body/div[1]/div/div/aside[3]/div/div[2]/div[2]/div/input")
    login_btn_locator = (By.XPATH, "/html/body/div[1]/div/div/aside[3]/div/div[2]/div[5]/div/button")
    database_tab_locator = (By.XPATH, "/html/body/section/aside/section/div[2]/div/div/div[1]/div/ul/li[4]/a/span")
    backup_btn_locator = (By.XPATH,
                          "/html/body/section/section/section/div[1]/div/div[2]/div[2]/div/div/div[2]/div/div["
                          "2]/div/div[3]/table/tbody/tr[2]/td[6]/div/div/div/span[1]")
    download_btn_locator = (By.XPATH,
                            "/html/body/div[3]/div/div[2]/div[2]/div/div[1]/div/div[2]/div[1]/div/div[2]/div/div["
                            "4]/div[2]/table/tbody/tr[1]/td[7]/div/div/div/span[2]")
    logged_in_indicator = (By.XPATH, "//*[contains(text(),'欢迎')]")
    database_page_indicator = (By.XPATH, "//*[contains(text(),'数据库管理')]")

    @allure.step("登录操作")
    def login(self, username, password):
        self.is_click(self.advanced_btn_locator)
        self.is_click(self.proceed_link_locator)
        self.input_text(self.username_locator, username)
        self.input_text(self.password_locator, password)
        self.is_click(self.login_btn_locator)

    def is_logged_in(self):
        try:
            return bool(self.find_element(self.logged_in_indicator))
        except NoSuchElementException:
            return False

    @allure.step("进入数据库页面")
    def navigate_to_database(self):
        self.is_click(self.database_tab_locator)

    def is_on_database_page(self):
        try:
            return bool(self.find_element(self.database_page_indicator))
        except NoSuchElementException:
            return False

    @allure.step("执行数据库备份")
    def backup_database(self):
        return self._retry_click(self.backup_btn_locator, "备份")

    @allure.step("下载备份文件")
    def download_backup(self):
        return self._retry_click(self.download_btn_locator, "下载")

    def _retry_click(self, locator, action_name):
        max_retries = 3
        for attempt in range(max_retries):
            try:
                btn = WebDriverWait(self.driver, 15).until(
                    EC.presence_of_element_located(locator)
                )
                WebDriverWait(self.driver, 5).until(
                    EC.element_to_be_clickable(btn)
                ).click()
                log.info(f"{action_name}操作成功")
                return True
            except StaleElementReferenceException:
                log.warning(f"元素失效，第{attempt + 1}次重试...")
                continue
            except Exception as e:
                log.error(f"{action_name}操作失败: {str(e)}")
                raise
        raise Exception(f"无法完成{action_name}，已重试{max_retries}次")

    # 在 test_backup.py 底部添加：

    def main(self):
        import pytest
        pytest.main([__file__, "-v", "--html=reports/report.html", "--self-contained-html"])


if __name__ == '__main__':
    BackupPage(pages.webpage.WebPage).main()
